

// #ifdef H5
const u = navigator.userAgent
/**
 * ios环境
 */
export const isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)

/**
 * android环境
 */
export const isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1
// #endif




window.cdzCallbackMethodToken = 0
window.cdzCallbackMap = {}

/**
 * 调用原生方法
 * @param {*} name 方法名
 * @param {*} params 参数
 * @param {*} cbk 回调
 * native传给js的值格式约定：
 result:
 {
  data:{
    k1:v1,
    k2:v2,
    ...
  },
  msg:msg,//附带的信息
  code:0-失败,1- 成功
 }
 */
export const cdzCallNative = (name, params, cbk) => {
	console.log('cdz调用 方法名:', name, '方法参数:', params, '回调:', cbk)

	/**
	 * cdz回调
	 * @param {*} extra
	 * @param {*} result
	 */
	function cdzCallback(extra, result) {
		let callbackMethod = window.cdzCallbackMap[extra]
		window.cdzCallbackMap[extra] = null
		console.log("rr1:" + JSON.stringify(result))

		console.log('callbackMethod', callbackMethod)
		if (callbackMethod) {
			let res = result.data
			// if (isAndroid) {
			//   res = result.data
			// }
			// if (isIOS) {
			//   res = result.data
			// }
			callbackMethod && callbackMethod(res)
		}
	}

	window.cdzCallback = cdzCallback

	/**
	 * 组合参数
	 * @param {*} obj
	 * @param {*} callback
	 */
	function composeParams(obj = null, callback = null) {
		let callbackMethodToken = null
		if (callback) {
			callbackMethodToken = (window.cdzCallbackMethodToken++).toString()
			window[`cdzCallback${callbackMethodToken}`] = callback
			window.cdzCallbackMap[callbackMethodToken] = window[`cdzCallback${callbackMethodToken}`]
		}
		return JSON.stringify({
			data: obj,
			callback: 'cdzCallback',
			extra: callbackMethodToken,
		})
	}

	let tjParams = composeParams(params, cbk)
	console.log('调用参数:' + tjParams)
	if (isAndroid && window.tj) {
		let _method = window.tj[name]
		_method && window.tj[name](tjParams)
	} else if (isIOS && window.webkit) {
		console.log('cdz调用iOS 方法名:', name, '方法参数:', params, '回调:', cbk)
		let _method = window.webkit.messageHandlers[name]
		_method && window.webkit.messageHandlers[name].postMessage(tjParams)
	}
}

export const nativeCall = (nameParams, params, callback = null) => {
	let name = typeof nameParams === 'string' ? nameParams : ''
	cdzCallNative(name, params, callback)
}

/*
    e.
    调用微信支付
    nativeCall('callWechatPay', data, cb)
    调用扫一扫
    nativeCall('scan', null, cb)
*/